//
//  SGspecificTableVC.swift
//  songguo
//
//  Created by 潘传洲 on 16/6/10.
//  Copyright © 2016年 pcz. All rights reserved.
//

import UIKit
import AFNetworking

private let ID = "Specific"
class SGSpecificTableVC: UIViewController {

    var acticleTitle:String?
    
    var specificViewModels : [SGSpecificViewModel]?
    
        /// 数据模型
    var specificModel : SGSpecificModel?{
        didSet{
            dealData()
        }
    }
    
        /// 展示的tableView
    lazy var tableView : UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.y = 0
        tableView.backgroundColor = UIColor.clearColor()
        tableView.width = screenWidth
        tableView.height = screenHeight
        tableView.separatorStyle = .None
        tableView.contentInset = UIEdgeInsetsMake(255, 0, 44, 0)
        
        let frame = CGRect(x: 0, y: 0, width: 320, height: 55)
        let view = UIView(frame: frame)
        view.backgroundColor = UIColor.redColor()
        tableView.tableHeaderView = view
        
        return tableView
    }()
    
        /// 顶部视图
    lazy var topImageView : UIImageView = {
        let topImageView = UIImageView()
        topImageView.frame = CGRect(x: 0, y: -255 / 2, width: screenWidth, height: 255)
        topImageView.contentMode = .ScaleAspectFill
        topImageView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
        return topImageView
    }()
    
     /// 最上方的遮盖视图
    lazy var coverView : UIView = {
        let coverView = UIView()
        coverView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 64)
        
        let gradientLayer = CAGradientLayer()
        
        gradientLayer.colors = [UIColor.whiteColor().CGColor,UIColor.clearColor().CGColor]
        gradientLayer.frame = coverView.frame
        coverView.layer.addSublayer(gradientLayer)
        return coverView
    }()
    
    override func viewDidLoad() {
        
        setupView()
        setupNavigationBar()
        super.viewDidLoad()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.alpha = 1
    }
}

extension SGSpecificTableVC{
    /**
     一次性加载的界面
     */
    func setupView() {
        // 添加子view
        view.addSubview(topImageView)
        view.addSubview(tableView)
//        view.addSubview(coverView)
        view.backgroundColor = UIColor.whiteColor()
        automaticallyAdjustsScrollViewInsets = false
    }
    
    /**
     处理模型
     */
    func dealData() {
        
        if specificModel is SGActivityModel {// SGActivityModel
            let activityModel = specificModel as! SGActivityModel
            specificViewModels = activityModel.specificViewModels!
            topImageView.sd_setImageWithURL(NSURL(string: activityModel.topImageUrl!), placeholderImage: UIImage(named: "home_cell_placeholderImage"))
            
        }else{// SGArticleModel
            let articleModel = specificModel as! SGArticleModel
            specificViewModels = articleModel.specificViewModels!
            topImageView.sd_setImageWithURL(NSURL(string: articleModel.topImageUrl!), placeholderImage: UIImage(named: "home_cell_placeholderImage"))
            
        }
    }
    
    /**
     设置导航条
     */
    func setupNavigationBar() {
        // 设置导航栏上的按钮
        let backBtn = creatBarButtonItem("nav_back_44x44_", action: #selector(back))
        navigationItem.leftBarButtonItem = backBtn
        
        let shareBtn = creatBarButtonItem("share_44x44_", action: #selector(share))
        let markBtn = creatBarButtonItem("mark_44x44_", action: #selector(mark))
        navigationItem.setRightBarButtonItems([markBtn,shareBtn], animated: true)
        
        // 设置导航栏背景
        navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
    }
    
    /**
     返回父控制器
     */
    func back() {
        navigationController?.popViewControllerAnimated(true)
    }
    
    /**
     点击了分享按钮
     */
    func share() {
        print("点击了分享按钮")
    }
    
    /**
     点击了标记按钮
     */
    func mark() {
        print("点击了标记按钮")
    }
    /**
     根据图片名称创建导航条上的按钮
     
     - parameter imageNanmed: 图片
     
     - returns: 按钮
     */
    func creatBarButtonItem(imageNanmed:String,action:Selector) -> UIBarButtonItem {
        let btn = UIButton(type: .Custom)
        btn.addTarget(self, action: action, forControlEvents: .TouchUpInside)
        btn.setBackgroundImage(UIImage(named: imageNanmed), forState: .Normal)
        btn.sizeToFit()
        let backBtnItem = UIBarButtonItem(customView: btn)
        return backBtnItem
    }
}

// MARK: - Table view data source 数据源
extension SGSpecificTableVC : UITableViewDataSource{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return specificViewModels!.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(ID) as? SGSpecificTableViewCell
        if cell == nil {
            cell = SGSpecificTableViewCell(style: .Default, reuseIdentifier: ID)
        }
        
        cell!.specificViewModel = specificViewModels![indexPath.row]
        
        return cell!
    }
    
}

// MARK: - Table view data delegate 代理
extension SGSpecificTableVC : UITableViewDelegate{
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return specificViewModels![indexPath.row].cellHeight!
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let offSetY = scrollView.contentOffset.y
        let changeY = offSetY + 255
        let scale = -offSetY / 255
        if scale > 1 {
            topImageView.transform = CGAffineTransformMakeScale(scale, scale)
        }else{
            topImageView.transform = CGAffineTransformMakeTranslation(0, -changeY / 2)
        }
    }
}